﻿using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace FrameworkCore.Extensions;

public static class StringExtensions
{
    /// <summary>
    /// 生成MD5哈希
    /// </summary>
    /// <param name="input">要哈希的原始字符串</param>
    /// <param name="salt">可选的盐值</param>
    /// <returns>MD5哈希</returns>
    public static string MDString(this string input, string? salt = "NM")
    {
        var inputBytes = Encoding.UTF8.GetBytes(input + (salt ?? ""));
        var hashBytes = MD5.HashData(inputBytes);
        return Convert.ToHexString(hashBytes);
    }

    /// <summary>
    /// 将字符串转换为 Int64（长整数）类型。如果转换失败，返回默认值。
    /// </summary>
    /// <param name="input">要转换的字符串</param>
    /// <param name="defaultValue">转换失败时返回的默认值</param>
    /// <returns>转换后的 Int64 值或默认值</returns>
    public static long ToInt64OrDefault(this string input, long defaultValue = 0)
    {
        if (long.TryParse(input, out long result))
        {
            return result;
        }

        return defaultValue;
    }

    /// <summary>
    /// 检查字符串是否为 null 或空字符串
    /// </summary>
    /// <param name="input">要检查的字符串</param>
    /// <returns>如果字符串为 null 或空字符串，则返回 true；否则返回 false</returns>
    public static bool IsNullOrEmpty(this string? input)
    {
        return string.IsNullOrEmpty(input);
    }

    /// <summary>
    /// 检查字符串是否为 null、空字符串或只包含空白字符
    /// </summary>
    /// <param name="input">要检查的字符串</param>
    /// <returns>如果字符串为 null、空字符串或只包含空白字符，则返回 true；否则返回 false</returns>
    public static bool IsNullOrWhiteSpace(this string? input)
    {
        return string.IsNullOrWhiteSpace(input);
    }

    //public static T ToObject<T>(this string json)
    //{
    //    if (string.IsNullOrWhiteSpace(json))
    //        return default(T)!;

    //    var options = new JsonSerializerOptions();
    //    options.PropertyNameCaseInsensitive = true;
    //    options.Converters.Add(new JsonStringEnumConverter());

    //    return JsonSerializer.Deserialize<T>(json, options)!;
    //}
    public static T ToObject<T>(this string json)
    {
        if (string.IsNullOrWhiteSpace(json))
            return default(T)!;
        return JsonConvert.DeserializeObject<T>(json)!;
    }
}
